package util

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
	"reflect"
)

const (
	SUCCESS int = 0 //操作成功
	FAILURE int = 1 //失败
)

//成功
func Success(ctx *gin.Context, data interface{}) {
	if data == nil {
		data = gin.H{}
	}
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"code": SUCCESS,
		"msg":  "Success",
		"data": data,
	})
}

//失败
func Failed(ctx *gin.Context, msg interface{}) {
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"code": FAILURE,
		"msg":  msg,
		"data": gin.H{},
	})
}

/**
 *author:Leedong
 *notes: 获取验证字段的错误信息
 *date:12:07 上午 2022/7/31
 **/
func GetMsg(err error, obj interface{}) string {
	getObj := reflect.TypeOf(obj)
	if errs, ok := err.(validator.ValidationErrors); ok {
		for _, e := range errs {
			if f, exist := getObj.Elem().FieldByName(e.Field()); exist {
				return f.Tag.Get("msg")
			}
		}
	}
	return err.Error()
}
